package com.shcz.migu.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;


/**
 */
public class BitmapUtil {

    private final static int MAX_IMAGE_SIZE = 1024 * 150;
    private final static int MAX_IMAGE_WIDTH = 480;

    //for small image style
    //	private final static int MAX_IMAGE_SIZE_SMALL = 1024 * 200;
    private final static int MAX_IMAGE_WIDTH_SMALL = 128;

    /**
     * 获取图片文件的信息，是否旋转了90度，如果是则反转
     *
     * @param bitmap 需要旋转的图片
     * @param path   图片的路径
     */
    public static Bitmap reviewPicRotate(Bitmap bitmap, String path) {
        int degree = getPicRotate(path);
        Log.d("BitmapUtil", "degree = " + degree);
        if (degree != 0) {
            Matrix m = new Matrix();
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            m.setRotate(degree); // 旋转angle度
            try {
                bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, m, true);// 从新生成图片
            } catch (OutOfMemoryError e) {
                return bitmap;
            }
        }
        return bitmap;
    }

    public static Bitmap getBitmapFromPath(String path) {
        FileInputStream fis = null;
        Bitmap bitmap = null;
        try {
            fis = new FileInputStream(path);
            bitmap = BitmapFactory.decodeStream(fis);
            Matrix matrix = new Matrix();
            matrix.setRotate(90);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0,
                    bitmap.getWidth(), bitmap.getHeight(),
                    matrix, true);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bitmap;
    }

    public static void getNewFileFor90Rotate(String path) {
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        if (bitmap == null) {
            return;
        }
        Matrix m = new Matrix();
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        m.setRotate(90); // 旋转angle度
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, m, true);// 从新生成图片

        try {
            FileOutputStream out = new FileOutputStream(path);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            bitmap = null;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static String getNewFilePathFor90Rotate(String path) {
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        if (bitmap == null) {
            return path;
        }
        Matrix m = new Matrix();
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        m.setRotate(90); // 旋转angle度
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, m, true);// 从新生成图片

        String newFile = CommonUtils.getAppCacheImageDirPath() + DateUtil.formatISO8601Date(new Date()) + ".jpg";
        try {
            FileOutputStream out = new FileOutputStream(newFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            bitmap = null;

            new File(path).delete();
            return newFile;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return path;
    }

    /**
     * 读取图片文件旋转的角度
     *
     * @param path 图片绝对路径
     * @return 图片旋转的角度
     */
    public static int getPicRotate(String path) {
        int degree = 0;
        try {
            if (path == null || path.length() == 0) {
                return degree;
            }
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }


    /**
     * 将图片的旋转角度置为0
     *
     * @param path
     * @return void
     * @Title: setPictureDegreeZero
     * @date 2012-12-10 上午10:54:46
     */
    public static void setPictureDegreeZero(String path) {
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            // 修正图片的旋转角度，设置其不旋转。这里也可以设置其旋转的角度，可以传值过去，
            // 例如旋转90度，传值ExifInterface.ORIENTATION_ROTATE_90，需要将这个值转换为String类型的
            exifInterface.setAttribute(ExifInterface.TAG_ORIENTATION, "no");
            exifInterface.saveAttributes();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String createScaledImage(String sourceFile, int desiredWidth, int size) {
        if (CommonUtils.isEmpty(sourceFile)) {
            return null;
        }
        if (sourceFile.lastIndexOf('.') < 0) {
            return null;
        }

        String destinationFile = CommonUtils.getAppCacheImageDirPath() + new Date().getTime()
                + ".dest.jpg";

        try {
            if (createScaledImage(sourceFile, destinationFile, desiredWidth, size)) {
                return destinationFile;
            }
        } catch (OutOfMemoryError e) {
            System.gc();
            return "";
        }

        return sourceFile;
    }

    public static String createScaledImageByFilter(String sourceFile, int desiredWidth, int size) {
        if (CommonUtils.isEmpty(sourceFile)) {
            return null;
        }
        if (sourceFile.lastIndexOf('.') < 0) {
            return null;
        }

        String destinationFile = CommonUtils.getAppCacheImageDirPath() + new Date().getTime()
                + ".dest.jpg";

        try {
            if (createScaledImageFilter(sourceFile, destinationFile, desiredWidth, size)) {
                return destinationFile;
            }
        } catch (IOException e) {
            System.gc();
            return "";
        }

        return sourceFile;
    }


    public static String createScaledImage(String sourceFile, int desiredWidth) {
        if (CommonUtils.isEmpty(sourceFile)) {
            return null;
        }
        if (sourceFile.lastIndexOf('.') < 0) {
            return null;
        }

        String destinationFile = CommonUtils.getAppCacheImageDirPath() + new Date().getTime()
                + ".png";

        try {
            if (createScaledImage(sourceFile, destinationFile, desiredWidth, MAX_IMAGE_SIZE)) {
                return destinationFile;
            }
        } catch (OutOfMemoryError e) {

        }

        return sourceFile;
    }


    /**
     * @param sourceFile
     * @param desiredWidth 裁剪图片
     */
    public static Bitmap getScaledImage(String sourceFile, int desiredWidth) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(sourceFile, options);
        //
        int w = options.outWidth;
        int h = options.outHeight;
        int max = MAX_IMAGE_WIDTH;

        if (desiredWidth > 0) {
            max = desiredWidth;
        }


        int inSampleSize = 1;
        if (w > h && w > max) {//如果宽度大的话根据宽度固定大小缩放
            inSampleSize = (int) Math.ceil((double) w / max);
        } else if (w < h && h > max) {//如果高度高的话根据宽度固定大小缩放
            inSampleSize = (int) Math.ceil((double) h / max);
        } else {

        }
        if (inSampleSize <= 0)
            inSampleSize = 1;

        options.inJustDecodeBounds = false;
        options.inSampleSize = inSampleSize;
        Bitmap sampledSrcBitmap = null;
        try {
            sampledSrcBitmap = BitmapFactory.decodeFile(sourceFile, options);
        } catch (OutOfMemoryError e) {
            try {
                LogcatStorageHelper.getInstance().addLog("createScaledImage failed, OutOfMemoryError, degress image size");
                options = new BitmapFactory.Options();
                options.inSampleSize += 2;
                sampledSrcBitmap = BitmapFactory.decodeFile(sourceFile, options);
            } catch (Exception e2) {
                LogcatStorageHelper.getInstance().addLog("createScaledImage failed, OutOfMemoryError");
            }
        }

        if (sampledSrcBitmap == null || sampledSrcBitmap.getWidth() <= 0 || sampledSrcBitmap.getHeight() <= 0) {
            LogcatStorageHelper.getInstance().addLog("createScaledImage failed, sampledSrcBitmap == null" + (sampledSrcBitmap == null) +
                    " sampledSrcBitmap.getWidth() <= 0 || sampledSrcBitmap.getHeight() <= 0");
            return null;
        }

        ExifInterface exif = null;
        try {
            exif = new ExifInterface(sourceFile);
        } catch (IOException e1) {
            LogcatStorageHelper.getInstance().addLog("createScaledImage failed, 1 IOException " + e1.toString());
            e1.printStackTrace();
            return null;
        }

        int exifOrientation = exif
                .getAttributeInt(ExifInterface.TAG_ORIENTATION,
                        ExifInterface.ORIENTATION_NORMAL);

        int rotate = 0;

        switch (exifOrientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                rotate = 90;
                break;

            case ExifInterface.ORIENTATION_ROTATE_180:
                rotate = 180;
                break;

            case ExifInterface.ORIENTATION_ROTATE_270:
                rotate = 270;
                break;
        }
        Matrix matrix = new Matrix();
        matrix.reset();

        if (rotate != 0) {
            matrix.setRotate(rotate);
        }

        if (rotate > 0) {
            Bitmap scaledBitmap = Bitmap.createBitmap(sampledSrcBitmap, 0, 0,
                    sampledSrcBitmap.getWidth(), sampledSrcBitmap.getHeight(),
                    matrix, true);
            sampledSrcBitmap = null;
            sampledSrcBitmap = scaledBitmap;
        }

        Bitmap compBitmap = JPEGCompressImage(sampledSrcBitmap, MAX_IMAGE_SIZE);

        if (compBitmap == null || (inSampleSize == 1 && rotate == 0)) {
            compBitmap = sampledSrcBitmap;
        }
        return compBitmap;
    }


    /**
     * @param sourceFile      s
     * @param destinationFile d
     * @param desiredWidth    裁剪图片
     */
    public static boolean createScaledImage(String sourceFile,
                                            String destinationFile, int desiredWidth, int size) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(sourceFile, options);
        //
        int w = options.outWidth;
        int h = options.outHeight;
        int max = MAX_IMAGE_WIDTH;

        if (desiredWidth > 0) {
            max = desiredWidth;
        }

        int inSampleSize = 1;
        if (w > h && w > max) {//如果宽度大的话根据宽度固定大小缩放
            inSampleSize = (int) Math.ceil((double) w / max);
        } else if (w < h && h > max) {//如果高度高的话根据宽度固定大小缩放
            inSampleSize = (int) Math.ceil((double) h / max);
        } else {

        }
        if (inSampleSize <= 0)
            inSampleSize = 1;

        options.inJustDecodeBounds = false;
        options.inSampleSize = inSampleSize;
        Bitmap sampledSrcBitmap = null;
        try {
            sampledSrcBitmap = BitmapFactory.decodeFile(sourceFile, options);
        } catch (OutOfMemoryError e) {
            try {
                LogcatStorageHelper.getInstance().addLog("createScaledImage failed, OutOfMemoryError, degress image size");
                options = new BitmapFactory.Options();
                options.inSampleSize += 2;
                sampledSrcBitmap = BitmapFactory.decodeFile(sourceFile, options);
            } catch (Exception e2) {
                LogcatStorageHelper.getInstance().addLog("createScaledImage failed, OutOfMemoryError");
            }
        }

        if (sampledSrcBitmap == null || sampledSrcBitmap.getWidth() <= 0 || sampledSrcBitmap.getHeight() <= 0) {
            LogcatStorageHelper.getInstance().addLog("createScaledImage failed, sampledSrcBitmap == null" + (sampledSrcBitmap == null) +
                    " sampledSrcBitmap.getWidth() <= 0 || sampledSrcBitmap.getHeight() <= 0");
            return false;
        }

        ExifInterface exif = null;
        try {
            exif = new ExifInterface(sourceFile);
        } catch (IOException e1) {
            LogcatStorageHelper.getInstance().addLog("createScaledImage failed, 1 IOException " + e1.toString());
            e1.printStackTrace();
            return false;
        }

        int exifOrientation = exif
                .getAttributeInt(ExifInterface.TAG_ORIENTATION,
                        ExifInterface.ORIENTATION_NORMAL);

        int rotate = 0;

        switch (exifOrientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                rotate = 90;
                break;

            case ExifInterface.ORIENTATION_ROTATE_180:
                rotate = 180;
                break;

            case ExifInterface.ORIENTATION_ROTATE_270:
                rotate = 270;
                break;
        }
        Matrix matrix = new Matrix();
        matrix.reset();

        if (rotate != 0) {
            matrix.setRotate(rotate);
        }

        if (rotate > 0) {
            Bitmap scaledBitmap = Bitmap.createBitmap(sampledSrcBitmap, 0, 0,
                    sampledSrcBitmap.getWidth(), sampledSrcBitmap.getHeight(),
                    matrix, true);
            sampledSrcBitmap.recycle();
            sampledSrcBitmap = null;
            sampledSrcBitmap = scaledBitmap;
        }

        Bitmap compBitmap = JPEGCompressImage(sampledSrcBitmap, size);

        try {
            if (compBitmap == null && inSampleSize == 1 && rotate == 0) {
                return false;
            }
            if (compBitmap == null) {
                compBitmap = sampledSrcBitmap;
            }
            FileOutputStream out = new FileOutputStream(destinationFile);
            compBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            compBitmap.recycle();
            compBitmap = null;
        } catch (IOException e) {
            LogcatStorageHelper.getInstance().addLog("createScaledImage failed, 2 IOException " + e.toString());
            e.printStackTrace();
            return false;
        }

        return true;
    }


    public static boolean createScaledImageFilter(String sourceFile,
                                                  String destinationFile, int desiredWidth, int size) throws OutOfMemoryError, IOException {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(sourceFile, options);
        //
        int w = options.outWidth;
        int h = options.outHeight;
        int max = MAX_IMAGE_WIDTH;

        if (desiredWidth > 0) {
            max = desiredWidth;
        }

        int inSampleSize = 1;
        if (w > h && w > max) {//如果宽度大的话根据宽度固定大小缩放
            inSampleSize = (int) Math.ceil((double) w / max);
        } else if (w < h && h > max) {//如果高度高的话根据宽度固定大小缩放
            inSampleSize = (int) Math.ceil((double) h / max);
        } else {

        }
        if (inSampleSize <= 0)
            inSampleSize = 1;

        options.inJustDecodeBounds = false;
        options.inSampleSize = inSampleSize;
        Bitmap sampledSrcBitmap = null;
        //		try {
        sampledSrcBitmap = BitmapFactory.decodeFile(sourceFile, options);
        //		} catch (OutOfMemoryError  e) {
        //			try {
        //				LogcatStorageHelper.addLog("createScaledImage failed, OutOfMemoryError, degress image size");
        //				options = new BitmapFactory.Options();
        //				options.inSampleSize += 2;
        //				sampledSrcBitmap = BitmapFactory.decodeFile(sourceFile, options);
        //			} catch(Exception e2) {
        //				LogcatStorageHelper.addLog("createScaledImage failed, OutOfMemoryError");
        //			}
        //		}

        if (sampledSrcBitmap == null || sampledSrcBitmap.getWidth() <= 0 || sampledSrcBitmap.getHeight() <= 0) {
            LogcatStorageHelper.getInstance().addLog("createScaledImage failed, sampledSrcBitmap == null" + (sampledSrcBitmap == null) +
                    " sampledSrcBitmap.getWidth() <= 0 || sampledSrcBitmap.getHeight() <= 0");
            return false;
        }

        ExifInterface exif = null;
        try {
            exif = new ExifInterface(sourceFile);
        } catch (IOException e1) {
            LogcatStorageHelper.getInstance().addLog("createScaledImage failed, 1 IOException " + e1.toString());
            e1.printStackTrace();
            return false;
        }

        int exifOrientation = exif
                .getAttributeInt(ExifInterface.TAG_ORIENTATION,
                        ExifInterface.ORIENTATION_NORMAL);

        int rotate = 0;

        switch (exifOrientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                rotate = 90;
                break;

            case ExifInterface.ORIENTATION_ROTATE_180:
                rotate = 180;
                break;

            case ExifInterface.ORIENTATION_ROTATE_270:
                rotate = 270;
                break;
        }
        Matrix matrix = new Matrix();
        matrix.reset();

        if (rotate != 0) {
            matrix.setRotate(rotate);
        }

        if (rotate > 0) {
            Bitmap scaledBitmap = Bitmap.createBitmap(sampledSrcBitmap, 0, 0,
                    sampledSrcBitmap.getWidth(), sampledSrcBitmap.getHeight(),
                    matrix, true);
            sampledSrcBitmap.recycle();
            sampledSrcBitmap = null;
            sampledSrcBitmap = scaledBitmap;
        }

        Bitmap compBitmap = JPEGCompressImage(sampledSrcBitmap, size);

        try {
            if (compBitmap == null && inSampleSize == 1 && rotate == 0) {
                return false;
            }
            if (compBitmap == null) {
                compBitmap = sampledSrcBitmap;
            }
            FileOutputStream out = new FileOutputStream(destinationFile);
            compBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            compBitmap.recycle();
            compBitmap = null;
        } catch (IOException e) {
            LogcatStorageHelper.getInstance().addLog("createScaledImage failed, 2 IOException " + e.toString());
            e.printStackTrace();
            return false;
        }

        return true;
    }


    /**
     * @param image
     * @return JPEG压缩图片，图片小于MAX_IMAGE_SIZE时候，不压缩，直接return当前图片
     */
    public static Bitmap JPEGCompressImage(Bitmap image, int size) {
        if (image == null) {
            return null;
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中

        boolean isCompressed = false;

        int max = MAX_IMAGE_SIZE;
        if (size > max) {
            max = MAX_IMAGE_SIZE;
        } else {
            max = size;
        }

        Log.d("BitmapUtil", "compress start baos.toByteArray().length " + baos.toByteArray().length + " max: " + max);

        if (baos.toByteArray().length > max) {
            float options2 = (max) / ((float) baos.toByteArray().length);
            int options = (int) (options2 * 100);
            Log.d("BitmapUtil", "compress start options: " + options);
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中

            Log.d("BitmapUtil", "compress end length: " + baos.toByteArray().length);
            isCompressed = true;
        }

        if (!isCompressed) {
            return null;
        } else {
            ByteArrayInputStream isBm = new ByteArrayInputStream(
                    baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
            try {
                Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
                return bitmap;
            } catch (OutOfMemoryError e) {

            }
        }
        return null;
    }

	/*public static Bitmap losslessComp(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		//判断如果图片大于1M,进行压缩避免在生成图片
		//（BitmapFactory.decodeStream）时溢出
		if( baos.toByteArray().length > MAX_IMAGE_SIZE) {
			baos.reset();//重置baos即清空baos
			//这里压缩50%，把压缩后的数据存放到baos中
			image.compress(Bitmap.CompressFormat.JPEG, 50, baos);
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		//开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		//现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
		float hh = 800f;//这里设置高度为800f
		float ww = 480f;//这里设置宽度为480f
		//缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;//be=1表示不缩放
		if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;//设置缩放比例
		//重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		isBm = new ByteArrayInputStream(baos.toByteArray());
		bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		return qualityComp(bitmap);//压缩好比例大小后再进行质量压缩
	}*/

    /**
     * 质量压缩
     *
     * @param image
     * @return
     */
    public static Bitmap qualityComp(Bitmap image, Context context) {
        if (image == null) {
            Toast.makeText(context, "选择图片失败", Toast.LENGTH_SHORT).show();
            return null;
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        //质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        int options = 100;
        //循环判断如果压缩后图片是否大于100kb,大于继续压缩
        while (baos.toByteArray().length > MAX_IMAGE_SIZE) {
            //重置baos即清空baos
            baos.reset();
            //这里压缩options%，把压缩后的数据存放到baos中
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);
            options -= 10;//每次都减少10
        }
        //把压缩后的数据baos存放到ByteArrayInputStream中
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        //把ByteArrayInputStream数据生成图片
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
        return bitmap;
    }

    /**
     * 图片按比例大小压缩方法
     *
     * @param srcPath
     * @return
     */
    public static Bitmap scaleComp(String srcPath, Context context) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        //此时返回bm为空
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = ConvertDipPx.getWindowHeight(context);
        float ww = ConvertDipPx.getWindowWidth(context);
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;//设置缩放比例
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return qualityComp(bitmap, context);//压缩好比例大小后再进行质量压缩
    }

    /**
     * 显示本地图片
     *
     * @param url
     * @return Bitmap
     */
    public static Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);  ///把流转化为Bitmap图片
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @param context
     * @param uri
     * @return
     */
    public static Bitmap decodeUriAsBitmap(Context context, Uri uri) {
        if (context == null || uri == null)
            return null;

        Bitmap bitmap;
        try {
            bitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }

    public static String getImageLocalPath(Context context, Bitmap bmp) {

//        String str = context.getFilesDir() + "/"+fileName+".png";
        String str = CommonUtils.getAppCacheImageDirPath() + new Date().getTime() + "camera.dest.jpg";
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(str);
            if (null != fos) {
                bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.flush();
                fos.close();
            }
        } catch (Exception e) {
        }

        return str;
    }

    public static Bitmap resizeImage(Bitmap bitmap, int w, int h) {
        Bitmap BitmapOrg = bitmap;
        int width = BitmapOrg.getWidth();
        int height = BitmapOrg.getHeight();
        int newWidth = w;
        int newHeight = h;

        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // if you want to rotate the Bitmap
        // matrix.postRotate(45);
        Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
                height, matrix, true);
        return resizedBitmap;
    }

    public static Bitmap resizeImage(Bitmap bitmap, float w, float h) {
        Bitmap BitmapOrg = bitmap;
        int width = BitmapOrg.getWidth();
        int height = BitmapOrg.getHeight();
        float newWidth = w;
        float newHeight = h;

        float scaleWidth = newWidth / width;
        float scaleHeight = newHeight / height;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // if you want to rotate the Bitmap
        // matrix.postRotate(45);
        Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
                height, matrix, true);
        return resizedBitmap;
    }

    public static String putFilePath(String uriPath) {
        if (TextUtils.isEmpty(uriPath)) {
            Log.e("file", "file path is empty!");
            return "";
        }

        String path = Uri.parse(uriPath).getPath();
        File file = new File(path);
        Log.d("piclength", file.length() + "");
        String fileName = file.getName();
        return fileName;
    }

    public static String getBtpFilePath(Bitmap bitmap) {
        String filePath = CommonUtils.getFundFilesDirPath() + System.currentTimeMillis() + ".jpg";//照片保存路径
        BufferedOutputStream bos = null;
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                file.createNewFile();
                bos = new BufferedOutputStream(new FileOutputStream(file));
                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bos);//将图片压缩到流中
                return filePath;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
